<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        background-color: #333;
      }
    </style>
  </head>
  <body>
    <script>
      const limitRequest = (urls, limit) => {
        // 存储请求结果
        const results = [];
        // 当前请求个数
        let activeUrlCount = 0;

        return new Promise((resolve, reject) => {
          const requestNext = () => {
            // 已经请求完成
            if (urls.length === 0 && activeUrlCount === 0)
              return resolve(results);

            while (activeUrlCount < limit && urls.length > 0) {
              const url = urls.shift();
              activeUrlCount += 1;

              fetch(url)
                .then((response) => response.json())
                .then((data) => results.push(data))
                .catch((error) => results.push(error.message))
                .finally(() => {
                  activeUrlCount -= 1;
                  requestNext();
                });
            }
          };
          requestNext();
        });
      };

      const urls = [
        'https://img.xjh.me/random_img.php',
        'https://img.xjh.me/random_img.php',
        'https://img.xjh.me/random_img.php',
      ];
      const cancelRequest = limitRequest(urls, 1).then((result) =>
        console.log(result)
      );
    </script>
  </body>
</html>
